package com.zzvcom.wc;

import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 先mapper,后reducer
 */
public class WordCoutMapper extends Mapper<LongWritable, Text, Text, LongWritable> {

    private static final LongWritable ONE = new LongWritable(1);
    private static final Logger logger = LoggerFactory.getLogger(WordCoutMapper.class);

    /**
     * @param key     数据的行号 0 1 2，这里无用
     * @param value   每行的数据
     * @param context 收集处理后的数据
     * @throws IOException
     * @throws InterruptedException
     */
    @Override
    protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, LongWritable>.Context context) throws IOException, InterruptedException {
        try {
            if (value == null) {
                return;
            }

            String line = value.toString();
            if (line.isEmpty()) {
                return;
            }

            String[] split = line.split(" ");
            for (String word : split) {
                if (word != null && !word.trim().isEmpty()) {
                    context.write(new Text(word), ONE);
                }
            }
        } catch (Exception e) {
            logger.error("Error processing line: " + value, e);
            throw new IOException("Failed to process input line", e);
        }
    }
}
